#include "Cache/TimerManager.hh"
#include "Cache/CacheManager.hh"
#include "Log/Log.hh"
#include <sys/timerfd.h>
#include <unistd.h>
#include <thread>

using std::this_thread::get_id;

TimerManager* TimerManager::_instance = nullptr;

TimerManager::TimerManager(int initSec, int peridocSec)
    : _timerfd(createTimerFd())
    , _initSec(initSec)
    , _periodSec(peridocSec){
    Log::debug("TimerManager init");
    setTimerFd(_initSec, _periodSec);
}

TimerManager* TimerManager::createTimer(int initSec, int peridocSec){
    if(_instance == nullptr){
        _instance = new TimerManager(initSec, peridocSec);
    }
    return _instance;
}

void TimerManager::destoryTimer(){
    if(_instance != nullptr){
        delete _instance;
        _instance = nullptr;
    }
}

int TimerManager::createTimerFd(){
    int fd = ::timerfd_create(CLOCK_REALTIME, 0);
    if(fd == -1){
        Log::error("[%s:%s:%d] %s", __FILE__, __func__, __LINE__, "create timerfd error");
    }
    return fd;
}

void TimerManager::setTimerFd(int initSec, int periodSec){
    struct itimerspec newValue;
    newValue.it_value.tv_sec = initSec;//起始时间
    newValue.it_value.tv_nsec = 0;

    newValue.it_interval.tv_sec = periodSec;//时间间隔（周期时间）
    newValue.it_interval.tv_nsec = 0;

    int ret = ::timerfd_settime(_timerfd, 0, &newValue, nullptr);
    if(ret == -1){
        Log::error("[%s:%s:%d] %s", __FILE__, __func__, __LINE__, "set timerfd error");
    }
}



int TimerManager::getTimerFd(){
    return _timerfd;
}



void TimerManager::beginTimerTask(){
    Log::debug("定时任务的线程号为: %lld", get_id());
    Log::info("定时任务开始");
    CacheManager::createCacheManager()->update();
    Log::info("定时任务结束");
}



TimerManager::~TimerManager(){
    ::close(_timerfd);
}
